import dayjs from 'dayjs';
import express from 'express';
import md5 from 'md5';
const router = express.Router();

// const fs = require('fs');
// const path = require('path');

// const app = express();
// const uploadDir = path.join(__dirname, 'uploads');
router.post('/out/upload/sliceUpload', (req, res) => {
	res.send('上传成功');

	const chunkIndex = parseInt(req.headers['upload-index']);
	const totalChunks = parseInt(req.headers['total-chunks']);
	const totalSize = parseInt(req.headers['total-size']);
	const filePath = path.join(uploadDir, `temp-${req.headers['filename']}`);
	const stream = fs.createWriteStream(filePath, { flags: 'a', start: chunkIndex * req.headers['chunk-size'] });
	req.pipe(stream);
	stream.on('finish', () => {
		res.sendStatus(200);
		if (chunkIndex === totalChunks - 1) {
			const finalFilePath = path.join(uploadDir, `final-${req.headers['filename']}`);
			const outputStream = fs.createWriteStream(finalFilePath);
			for (let i = 0; i < totalChunks; i++) {
				const chunkPath = path.join(uploadDir, `temp-${req.headers['filename']}-${i}`);
				const inputStream = fs.createReadStream(chunkPath);
				inputStream.pipe(outputStream, { end: false });
				inputStream.on('end', () => {
					fs.unlinkSync(chunkPath);
					if (i === totalChunks - 1) {
						console.log('文件合并完成');
					}
				});
			}
		}
	});
});

export default router;


